<template>
    <div>
        <el-row>
            <el-button type="primary" @click="updateDialogVisible = true">更新</el-button>
        </el-row>
        <el-row>
            <el-col :span="24">
                <div id="map" class="map-chart"></div>
            </el-col>
        </el-row>

        <!-- 添加数据 -->
        <el-dialog title="添加数据" :visible.sync="createDialogVisible" width="30%">
            <el-form label-width="80px" size="small" ref="createForm" :model="createForm" :rules="createRules">
                <el-form-item label="省">
                    <el-input v-model="createForm.province" placeholder="" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="市">
                    <el-input v-model="createForm.city" placeholder="" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="区/县">
                    <el-input v-model="createForm.district" placeholder="" :disabled="true"></el-input>
                </el-form-item>
                <el-form-item label="拼音" prop="pinyin">
                    <el-input v-model="createForm.pinyin" placeholder="" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="adcode" prop="adcode">
                    <el-input v-model="createForm.adcode" placeholder="" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="geo" prop="geo">
                    <el-input type="textarea" v-model="createForm.geo"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('createForm')">添加</el-button>
                    <el-button @click="createDialogVisible = false">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>

        <!-- 更新数据 -->
        <el-dialog :visible.sync="updateDialogVisible" width="30%">
            <el-form label-width="80px" size="small" ref="updateForm" :model="updateForm" :rules="updateRules">
                <el-form-item label="省" prop="province_id">
                    <el-select v-model="updateForm.province_id" placeholder="请选择省" @change="getCityList">
                        <el-option v-for="province in provinceList" :key="province.id" :label="province.name" :value="
                            province.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="市" prop="city_id">
                    <el-select v-model="updateForm.city_id" placeholder="请选择市" @change="getDistrictList">
                        <el-option v-for="city in cityList" :key="city.id" :label="city.name" :value="
                            city.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="区/县" prop="district_id">
                    <el-select v-model="updateForm.district_id" placeholder="请选择区/县" @change="districtChange">
                        <el-option v-for="district in districtList" :key="district.id" :label="district.name" :value="
                            district.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="名称" prop="name">
                    <el-input v-model="updateForm.name" placeholder=""></el-input>
                </el-form-item>
                <el-form-item label="pinyin" prop="pinyin">
                    <el-input v-model="updateForm.pinyin" placeholder=""></el-input>
                </el-form-item>
                <el-form-item label="adcode" prop="adcode">
                    <el-input v-model="updateForm.adcode" placeholder="" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="geo" prop="geo">
                    <el-input type="textarea" v-model="updateForm.geo"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('updateForm')">更新</el-button>
                    <el-button @click="resetUpdateForm('updateForm')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>

</template>

<script>
import * as echarts from 'echarts';
import china from './china.js';
import { GetMaps, CreateMap, GetMap, UpdateMap, GetAddress } from '@/api/api';
export default {
    data() {
        return {
            adcodes: [], // 点击一次往里存一个adcode，判断是否省、市、区县
            provinceList: [],
            cityList: [],
            districtList: [],
            updateDialogVisible: false,
            createDialogVisible: false,
            createForm: {
                province: '',
                city: '',
                district: '',
                adcode: '',
                pinyin: '',
                geo: ''
            },
            updateForm: {
                province_id: '',
                city_id: '',
                district_id: '',
                name: '',
                adcode: '',
                pinyin: '',
                geo: ''
            },
            createRules: {
                adcode: [
                    { required: true, message: '请输入adcode', trigger: 'blur' }
                ],
                pinyin: [
                    { required: true, message: '请输入名称的拼音', trigger: 'blur' }
                ],
                geo: [
                    { required: true, message: '请输入geo数据', trigger: 'blur' }
                ]
            },
            updateRules: {
                province_id: [
                    { required: true, message: '请选择省', trigger: 'change' }
                ],
                name: [
                    { required: true, message: '请输入地区名称', trigger: 'blur' }
                ],
                adcode: [
                    { required: true, message: '请输入adcode', trigger: 'blur' }
                ],
                pinyin: [
                    { required: true, message: '请输入名称的拼音', trigger: 'blur' }
                ],
                geo: [
                    { required: true, message: '请输入geo数据', trigger: 'blur' }
                ]
            },
            district_city: ['北京市','天津市','上海市','重庆市'],
        }
    },
    methods: {
        getMapOption(name) {
            return {
                geo: { map: name, roam: false, emphasis: { label: { show: false, }, }, },
                series: [
                    {
                        name: '地域分布',
                        type: 'map',
                        coordinateSystem: 'geo',
                        map: name,
                        data: [],
                    },
                ],
                toolbox: {
                    show: true,
                    feature: {
                        myTool1: {
                            show: true,
                            title: "返回",
                            icon: "path://M512 64L64 512l448 448 192-192L448 512l256-256z",
                            onclick: () => {
                                this.adcodes.pop();
                                let adcode = '';
                                if (this.adcodes.length != 0) {
                                    adcode = this.adcodes[this.adcodes.length - 1]['adcode'];
                                }
                            
                                this.renderMap(adcode);
                            },
                        }
                    }
                }
            }
        },
        async renderMap(adcode = ''){
            this.$manageMapChart.showLoading();

            let mapOption;
            if (adcode == '') {
                // 初始化
                echarts.registerMap('china', china);
                mapOption = this.getMapOption('china');

                const res = await GetMaps(0);
                if (res.code !== '0') {
                    this.$message.error('获取地图数据失败');
                } else {
                    mapOption.series[0].data = res.data;
                }
            } else {
                const res = await GetMap(adcode);
                if (res.code !== '0') {
                    this.$message.error(res.msg);
                    return;
                }
                if (res.data == null) {
                    this.$message.error('该区域暂无数据');
                    return;
                }
                echarts.registerMap(res.data.pinyin, res.data.geo);

                mapOption = this.getMapOption(res.data.pinyin);

                if (this.adcodes.length <= 2) {
                    // 获取下级的地图,到区县级就不再下钻
                    const childrenMapsRes = await GetMaps(res.data.id);
                    if (childrenMapsRes.code !== '0') {
                        // 这里不用return，没有数据不渲染下级，不阻止地图渲染
                        this.$message.error(childrenMapsRes.msg);
                    }
                    mapOption.series[0].data = childrenMapsRes.data;
                }
            }

            this.$manageMapChart.setOption(mapOption);

            this.$manageMapChart.hideLoading();
        },
        getCityList(id) {
            this.cityList = [];
            this.districtList = [];
            this.updateForm.city_id = '';
            this.updateForm.district_id = '';
            GetAddress(id).then(res => {
                if (res.code === '0') {
                    this.cityList = res.data;
                }
            });
            this.provinceList.forEach(item => {
                if (item.id == id) {
                    this.updateForm.name = item.name;
                    return;
                }
            });
        },
        getDistrictList(id) {
            this.districtList = [];
            this.updateForm.district_id = '';
            GetAddress(id).then(res => {
                if (res.code === '0') {
                    this.districtList = res.data;
                }
            });
            this.cityList.forEach(item => {
                if (item.id == id) {
                    this.updateForm.name = item.name;
                    return;
                }
            });
        },
        districtChange(id) {
            this.districtList.forEach(item => {
                if (item.id == id) {
                    this.updateForm.name = item.name;
                    return;
                }
            });
        },
        submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (!valid) {
                    return false;
                } else {
                    if (formName == 'createForm') {
                        this.onCreateGeoData();
                    } else {
                        this.updateGeoData();
                    }
                }
            });
        },
        resetUpdateForm(formName) {
            this.$refs[formName].resetFields();
            this.updateDialogVisible = false;
            this.cityList = [];
            this.districtList = [];
        },
        async updateGeoData() {
            let id = 0;
            if (this.updateForm.district_id != '') {
                id = this.updateForm.district_id;
            } else if (this.updateForm.city_id != '') {
                id = this.updateForm.city_id;
            } else {
                id = this.updateForm.province_id;
            }
            const res = await UpdateMap({
                id: id,
                name: this.updateForm.name,
                adcode: this.updateForm.adcode,
                pinyin: this.updateForm.pinyin,
                geo: this.updateForm.geo
            });
            if (res.code !== '0') {
                this.$message.error(res.msg);
                return;
            }
            window.location.reload();
        },
        async onCreateGeoData() {
            const res = await CreateMap(this.createForm);
            if (res.code !== '0') {
                this.$message.error(res.msg);
                return;
            }
            window.location.reload();
        },
    },
    async mounted() {

        const res = await GetAddress(0);
        if (res.code == '0') {
            this.provinceList = res.data;
        }

        // 注册地图
        this.$manageMapChart = echarts.init(document.getElementById('map'));

        // 监听点击事件
        this.$manageMapChart.on('click', async (params) => {
            if (this.adcodes.length >= 3) {
                // 到了区县级，点击地图不再响应
                return;
            }
            if (params.componentType === 'series' && params.seriesType === 'map') {
                // 确保点击的是地图系列
                if (params.data == null) {
                    // 新增数据
                    // 先将省市区清空，避免显示点击未提交的数据
                    this.createForm.province = '';
                    this.createForm.city = '';
                    this.createForm.district = '';
                    if (this.adcodes.length == 0) {
                        // adcodes为空，说明是第一次新增地图
                        this.createForm.province = params.name;
                        if (this.district_city.includes(params.name)) {
                            // 直辖市 市级同省级
                            this.createForm.city = params.name;
                        }
                    } else if (this.adcodes.length == 1) {
                        // adcodes长度为1，说明是新增市的地图，adcodes[0]为省
                        this.createForm.province = this.adcodes[0].name;
                        // 判断下地图是从直辖市进来的吗
                        if (this.district_city.includes(this.adcodes[0].name)) {
                            this.createForm.city = this.adcodes[0].name;
                            this.createForm.district = params.name;
                        } else {
                            this.createForm.city = params.name;
                        }
                    } else {
                        if (this.district_city.includes(this.adcodes[0].name)) {
                            // 如果是直辖市，点击到区县级返回
                            return;
                        }
                        // 区县，要显示省市
                        this.createForm.province = this.adcodes[0].name;
                        this.createForm.city = this.adcodes[1].name;
                        this.createForm.district = params.name;
                    }
                    this.createDialogVisible = true;
                } else {
                    // 先将点击的地图数据入栈
                    this.adcodes.push({ adcode: params.data.adcode, name: params.name });
                    // 渲染地图
                    this.renderMap(params.data.adcode);
                }
            }
        });

        this.renderMap();
    },
    
}
</script>

<style scoped>
.map-chart {
    width: 100%;
    height: 700px;
}
</style>